import { App } from "vue";

export function lazyDom(app: App) {
  app.directive("lazy-dom", {
    mounted(el) {
      const observer = new IntersectionObserver(
        ([{ isIntersecting }]) => {
          if (isIntersecting) {
          }
        },
        { threshold: 0.01 }
      );
      observer.observe(el);
    },
    unmounted() {}
  });
}

export function lazy(app: App) {
  // 1. 图片懒加载指令
  app.directive("lazy", {
    // 生命周期
    // 先存储图片地址不能在src上，当图片进入可视区，将你存储图片地址设置给图片元素
    mounted(el, binding) {
      // 创建一个观察对象，来观察DOM是否进入可视区
      const observer = new IntersectionObserver(
        ([{ isIntersecting }]) => {
          if (isIntersecting) {
            // 停止观察
            observer.unobserve(el);
            // 把v-指令的之设置给src binding.value 指令的值
            el.src = binding.value;
          }
        },
        { threshold: 0.01 }
      );
      observer.observe(el);
    },
    updated(el, binding) {
      // 创建一个观察对象，来观察DOM是否进入可视区
      const observer = new IntersectionObserver(
        ([{ isIntersecting }]) => {
          if (isIntersecting) {
            observer.unobserve(el);
            el.src = binding.value;
          }
        },
        { threshold: 0.01 }
      );
      observer.observe(el);
    }
  });
}
